package code.commonAlgorithm;

import java.util.Arrays;

/**
 * @author cuihaoran
 * @date 2024/11/29
 */
public class KMP {

    private int[] getNext(String pattern) {
        char[] chars = pattern.toCharArray();
        int len = chars.length;
        int[] next = new int[len];
        int j = 0;
        for (int i = 1; i < len; i++) {
            while (j > 0 && chars[i] != chars[j])
                j = next[j - 1];
            if (chars[i] == chars[j])
                j++;
            next[i] = j;
        }
        return next;
    }

    public int kmp(String pattern, String s) {
        int[] next = getNext(pattern);
        char[] sChars = s.toCharArray();
        char[] pChars = pattern.toCharArray();
        int sLen = sChars.length, pLen = pChars.length;
        int j = 0;
        for (int i = 0; i < sLen; i++) {
            while (j > 0 && sChars[i] != pChars[j])
                j = next[j - 1];
            if (sChars[i] == pChars[j])
                j++;
            if (j == pLen)
                return i - j + 1;
        }
        return -1;
    }

    public static void main(String[] args) {
        KMP k = new KMP();
        System.out.println(Arrays.toString(k.getNext("ababcabc")));
    }
}
